import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/screens/cart/cart_page.dart';
import 'package:mall/screens/home/home_category_screen.dart';
import 'package:mall/screens/home/home_screen.dart';
import 'package:mall/screens/main/update_dialog.dart';
import 'package:mall/screens/message/message_page.dart';
import 'package:mall/screens/mine/mine_page.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';

import '../../constants.dart';

class MainPage extends StatefulWidget {
  static const routeName = '/MainPage';

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  GlobalKey<UpdateDialogState> _dialogKey = GlobalKey();

  final List<Widget> _pages = [
    HomeScreen(),
    HomeCategoryScreen(args: HomeCategoryScreenArgs(false)),
    MessagePage(),
    CartTabItemPage(),
    MinePage(),
  ];
  PageController _pageController;
  int _currentIndex = 0;
  DateTime _lastTime;

  @override
  void initState() {
    super.initState();
    FlutterBugly.init(
      androidAppId: bugly_android_app_id,
      iOSAppId: bugly_ios_app_id,
    );
    FlutterBugly.onCheckUpgrade.listen((event) {
      _showUpdateDialog(event.newFeature, event.apkUrl, event.upgradeType == 2);
    });

    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController.dispose();

    FlutterBugly.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        body: PageView.builder(
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) => _pages[index],
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: (index) => _onTapItem(index),
          items: [
            BottomNavigationBarItem(
              icon: ImageIcon(AssetImage("assets/icons/home.png")),
              activeIcon: ImageIcon(AssetImage("assets/icons/home_active.png")),
              label: "首页",
            ),
            BottomNavigationBarItem(
              icon: ImageIcon(AssetImage("assets/icons/category.png")),
              activeIcon: ImageIcon(AssetImage("assets/icons/category_active.png")),
              label: '分类',
            ),
            BottomNavigationBarItem(
              icon: ImageIcon(AssetImage("assets/icons/chat.png")),
              activeIcon: ImageIcon(AssetImage("assets/icons/chat_active.png")),
              label: '消息',
            ),
            BottomNavigationBarItem(
              icon: ImageIcon(AssetImage("assets/icons/cart.png")),
              activeIcon: ImageIcon(AssetImage("assets/icons/cart_active.png")),
              label: '购物车',
            ),
            BottomNavigationBarItem(
              icon: ImageIcon(AssetImage("assets/icons/mine.png")),
              activeIcon: ImageIcon(AssetImage("assets/icons/mine_active.png")),
              label: '我的',
            )
          ],
        ),
      ),
      onWillPop: _doubleCheck,
    );
  }

  /// 点击切换
  void _onTapItem(int index) {
    _pageController.jumpToPage(index);
    setState(() {
      _currentIndex = index;
    });
  }

  /// 双击返回
  Future<bool> _doubleCheck() async {
    // 点击返回键
    var now = DateTime.now();
    if (_lastTime == null || now.difference(_lastTime) > Duration(seconds: 2)) {
      _lastTime = now;
      EasyLoading.showToast('再按一次退出');
      return false;
    } else {
      return true;
    }
  }

  /// 显示升级提示
  void _showUpdateDialog(String version, String url, bool isForceUpgrade) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => _buildDialog(version, url, isForceUpgrade),
    );
  }

  /// 升级提示
  Widget _buildDialog(String version, String url, bool isForceUpgrade) {
    return WillPopScope(
      child: UpdateDialog(
        key: _dialogKey,
        version: version,
        onClickWhenDownload: (_msg) {},
        onClickWhenNotDownload: () {
          _downloadApk(url);
        },
      ),
      onWillPop: () async => isForceUpgrade,
    );
  }

  /// 下载Apk
  void _downloadApk(String url) async {
    try {
      // 目录
      final tempDir = await getApplicationDocumentsDirectory();
      final path = tempDir.path + '/Download/';
      final directory = Directory(path);
      if (!directory.existsSync()) {
        directory.createSync(recursive: true);
      }
      final savePath = path + 'mall.apk';
      debugPrint('目录：$path');
      // 下载
      await Dio().download(
        url,
        savePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            _updateProgress(received / total);
          }
        },
        options: Options(
          headers: {HttpHeaders.acceptEncodingHeader: "*"},
        ),
      );
      debugPrint('下载完成');
      // 安装
      await OpenFile.open(savePath);
    } catch (e) {
      debugPrint('$e');
    }
  }

  /// 下载进度
  void _updateProgress(double _progress) {
    setState(() {
      _dialogKey.currentState.progress = _progress;
    });
  }
}
